//
//  NLAnalyzer.m
//  LifeTracker_Test
//
//  Created by Petr Homola on 10/17/11.
//  Copyright (c) 2011 TapCrew. All rights reserved.
//

#import "NLAnalyzer.h"
#include "MorphologicalAnalyzer.h"
#include "Grammar.h"
#include "ListParser.h"

@implementation NLAnalyzer {
    nlp::EnglishMorphologicalAnalyzer* engAnalyzer;
    nlp::Grammar* grammar;
}

- (id)init {
    if ((self = [super init])) {
        NSString* path = [[NSBundle mainBundle] pathForResource: @"morph_en" ofType: @"txt"];
        engAnalyzer = new nlp::EnglishMorphologicalAnalyzer([path UTF8String]);
        path = [[NSBundle mainBundle] pathForResource: @"sample_en" ofType: @"gr"];
        NSError* error;
        NSString* s = [NSString stringWithContentsOfFile: path encoding: NSUTF8StringEncoding error: &error];
        nlp::ListParser parser([s UTF8String]);
        bool success;
        auto grammarList = parser.parse(success);
        NSLog(@"Grammar parsed: %d", success);
        if (success) grammar = new nlp::Grammar(grammarList);
    }
    return self;
}

- (void)analyzeText:(NSString*)text language:(NSString*)language callback:(void(^)(void*))callback {
    if ([language isEqualToString: @"en"]) {
        auto chart = engAnalyzer->chart([text UTF8String]);
        grammar->apply(&*chart);
        chart->enumerateShortestPaths(BLOCK()(nlp::PhrasePath* path) {
            callback(path);
        });
    } else {
        NSLog(@"Morph. analyzer: unknown language: %@", language);
    }
}

- (NSArray*)analyzeWord:(NSString*)word language:(NSString*)language {
    if ([language isEqualToString: @"en"]) {
        auto v = engAnalyzer->analyze([word UTF8String]);
        if (v == nullptr) return nil;
        NSMutableArray* result = [NSMutableArray array];
        for (auto it = v->begin(); it != v->end(); ++it) {
            [result addObject: [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSString stringWithUTF8String: it->getForm().c_str()], @"form",
                                [NSString stringWithUTF8String: it->getLemma().c_str()], @"lemma",
                                [NSString stringWithUTF8String: it->getTag().c_str()], @"tag",
                                nil]];
        }
        return [result count] > 0 ? result : nil;
    } else {
        NSLog(@"Morph. analyzer: unknown language: %@", language);
        return nil;
    }
}

- (void)dealloc {
    delete engAnalyzer;
    delete grammar;
    [super dealloc];
}

@end
